package com.liu.sx.service;

import com.liu.sx.common.util.IdWorker;
import com.liu.sx.dao.WormDao;
import com.liu.sx.entity.Worm;
import com.liu.sx.pojo.BW;
import com.liu.sx.util.BCD2String;
import com.liu.sx.util.BwUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.transaction.Transactional;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
@Transactional
public class WormService {

    @Autowired
    private WormDao wormDao;

    @Autowired
    private IdWorker idWorker;

    public void insert(BW bw){
        List<Worm> worms =pareFromBw(bw);
        for (Worm w:worms ) {
            w.setId(idWorker.nextId()+"");
            wormDao.save(w);
        }





    }

    private List<Worm> pareFromBw(BW bw) {
        byte[] msg = BwUtil.Object2byte(bw);
        byte [] rq = Arrays.copyOfRange(msg,10,13);
        String sbrq ="20"+ BCD2String.bcd2Str(rq);

        SimpleDateFormat df  = new SimpleDateFormat("yyyyMMdd");

        Date date = null;
        try {
            date = df.parse(sbrq);
        } catch (ParseException e) {
            log.info("时间解析错误");
        }

         long start_time = date.getTime();
//               解析虫子点位
        byte [] worm = Arrays.copyOfRange(msg,13,13+96);
        System.out.println(Arrays.toString(worm));
        System.out.println("worm"+worm.length);

        List<Worm> worms = new ArrayList<>();

        for(int i=0;i<worm.length;i++){

            Worm w1 = new Worm();
            w1.setAddress(bw.getAddress());
            // 处理负数的情况，前台数据传来的是一个负数 byte 转换成int 会有负数，这里要处理下
            w1.setCount( worm[i]&0xff);



            w1.setDateTime(new Date(start_time+i*900000));
//            System.out.println(new Date(start_time+i*900000));
            worms.add(w1);
        }
        return worms;
    }


    public Page<Worm> findPageByQuery(int num, int rows, String query) {
        if(num==0){
            num=1;
        }
        Pageable pageable = PageRequest.of(num-1,rows, Sort.Direction.DESC,"dateTime");
       return wormDao.findAll(query,pageable);


    }




}

